package com.vc.utils;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

// 请求过滤器 在每一个请求进入到controller之前过滤一下 校验jwt
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final PathMatcher pathMatcher = new AntPathMatcher();

    // 规定: 必须要重写的方法 当客户端请求来的时候就会进到方法里
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        try {
            // 看请求的目标url是不是受保护的url(需要登录权限)
            if(isProtectedUrl(request)) {
//                System.out.println(request.getMethod());

                // 发送请求的方法不是OPTIONS方法
                if(!request.getMethod().equals("OPTIONS"))
                    // 检验带来的token是否有效 能否解析出来有效的数据
                    // 如果校验成功了 返回的http对象就是CustomHttpServletRequest中定制的http对象
                    request = JwtUtils.validateTokenAndAddUserIdToHeader(request);
            }
        } catch (Exception e) {
            // 校验失败 抛出异常 打回请求
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
            return;
        }
        // 放行/打回 前端发送来的请求
        filterChain.doFilter(request, response);
    }

    private boolean isProtectedUrl(HttpServletRequest request) {
        // 定义受保护的url
        List<String> protectedPaths = new ArrayList<String>();
        protectedPaths.add("/ums/user/info");
        protectedPaths.add("/ums/user/update");
        protectedPaths.add("/post/create");
        protectedPaths.add("/post/update");
        protectedPaths.add("/post/delete/*");
        protectedPaths.add("/comment/add_comment");
        protectedPaths.add("/relationship/subscribe/*");
        protectedPaths.add("/relationship/unsubscribe/*");
        protectedPaths.add("/relationship/validate/*");

        boolean bFind = false;
        for( String passedPath : protectedPaths ) {
            // 对比发送来的请求与受保护的url
            bFind = pathMatcher.match(passedPath, request.getServletPath());
            if( bFind ) {
                break;
            }
        }
        return bFind;
    }

}